package com.daykw.xiaohongshu.task;

import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;
import org.quartz.DisallowConcurrentExecution;
import org.springframework.stereotype.Service;

import com.daykw.xiaohongshu.model.TAuthorTask;
import com.daykw.xiaohongshu.task.thread.AuthorJobThread;
import com.daykw.xiaohongshu.util.Const;
import com.daykw.xiaohongshu.util.QuartzManager;
import com.daykw.xiaohongshu.util.SpringContextHolder;

@DisallowConcurrentExecution
@Service
public class AuthorJob extends CustmTask {

	private static Logger logger = Logger.getLogger(AuthorJob.class);

	public void doStart() {
		logger.info("初始化获取LiajiaJobs任务...");
		try {
			if (QuartzManager.getTrigger("AuthorJob") == null) {
				QuartzManager.addJob("AuthorJob", this, "0/5 * * * * ?");
			} else {
				logger.info("已经存在任务:Jobs");
			}
		} catch (Exception e) {
			logger.error("", e);
		}
	}

	@Override
	public void doWork() {

		if (SpringContextHolder.getApplicationContext() == null) {
			try {
				TimeUnit.SECONDS.sleep(3);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			logger.info("等待上下文启动");
		}
		NutDao dao = SpringContextHolder.getBean("dao");
		try {
			if (Const.PAGE_THREAD > 0) {
				ExecutorService pool = this.getPool(Const.PAGE_THREAD);
				int node = new Random().nextInt(10);
				List<TAuthorTask> list = dao.query(TAuthorTask.class,
						Cnd.where("status", "=", 0).and("node", "=", node).limit(1, Const.PAGE_THREAD*3));
				// String[] ips = this.getIps();
				for (TAuthorTask task : list) {
					Thread thread = new Thread(new AuthorJobThread(task));
					try {
						pool.execute(thread);
						Thread.sleep(10);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

	}

}
